//
//  EMMBaseWebViewController.m
//  EMMApp
//
//  Created by Mac on 2017/9/23.
//  Copyright © 2017年 YiXun. All rights reserved.
//

#import "EMMBaseWebViewController.h"
#import <WebKit/WebKit.h>

@interface EMMBaseWebViewController ()<UIWebViewDelegate,WKNavigationDelegate,WKUIDelegate>

//定义WKWebView
@property ( nonatomic, strong) WKWebView *webView;


//设置请求时间
@property (nonatomic, strong) NSTimer *myTimer;

//刷新（房源详情页面带分享）数组
@property (nonatomic, strong) NSMutableArray *itmesNewArr;

//当前房源Id
@property (nonatomic, strong) NSString *nowHouseId;

//房间号
@property (nonatomic, strong) NSString *shareId;

//进度条
@property (nonatomic, strong) UIProgressView *progressView;

//添加透明返回按钮修改系统返回方法
@property (nonatomic, strong) UIButton *backButton;

@end

@implementation EMMBaseWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [super viewDidLoad];
    _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH, EMM_HEIGHT-SafeAreaTopHeight)];
    [_webView setAllowsBackForwardNavigationGestures:true];
    _webView.navigationDelegate = self;
    _webView.UIDelegate = self;
    [self.view addSubview:_webView];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[_urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
    [_webView loadRequest:request];
    //进度条
    self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 2)];
    self.progressView.trackTintColor = [UIColor whiteColor];
    self.progressView.progressTintColor = [UIColor colorFromHexCode:@"#F37006"];
    //设置进度条的高度，下面这句代码表示进度条的宽度变为原来的1倍，高度变为原来的1.5倍.
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
    //添加进度条监听
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [self.view addSubview:self.progressView];
    [self creatNavigationController];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

#pragma mark - 导航
- (void)creatNavigationController {
    [self updateNavBar];
    self.navigationItem.title = self.titleString;
    [self configLeftBtn];
}

#pragma mark - 监听web页面的标题与进度条
- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {
    
    if ([keyPath isEqualToString:@"title"]){
        if (object == self.webView) {
            
        }else{
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }else if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progressView.progress = self.webView.estimatedProgress;
        if (self.progressView.progress == 1) {
            /*
             *添加一个简单的动画，将progressView的Height变为1.4倍，在开始加载网页的代理中会恢复为1.5倍
             *动画时长0.25s，延时0.3s后开始动画
             *动画结束后将progressView隐藏
             */
            __weak typeof (self)weakSelf = self;
            [UIView animateWithDuration:0.25f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                weakSelf.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.4f);
            } completion:^(BOOL finished) {
                weakSelf.progressView.hidden = YES;
                
            }];
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark - WKWebView代理
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    NSString *urlStr = webView.URL.absoluteString;
    NSLog(@"Web开始请求地址:%@",urlStr);
    //限制请求时间
    self.progressView.hidden = NO;
    //开始加载网页的时候将progressView的Height恢复为1.5倍
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
    //防止progressView被网页挡住
    [self.view bringSubviewToFront:self.progressView];
    //限制请求时间
    [self performSelector:@selector(delayMethod) withObject:nil afterDelay:60];
}

// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    NSString *urlStr = webView.URL.absoluteString;
    NSLog(@"web开始返回数据地址了:%@",urlStr);

    
}

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    
}

// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
    NSString *urlStr = webView.URL.absoluteString;
    NSLog(@"Web请求失败地址:%@",urlStr);
}

// 接收到服务器跳转请求之后再执行
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {
    
}

//收到响应后是否决定跳转 判断当前地址
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    NSInteger statusCode = ((NSHTTPURLResponse *)navigationResponse.response).statusCode;
    if ( statusCode == 404) {
        decisionHandler(WKNavigationResponsePolicyCancel);//不加载当前页面
        NSLog(@"错误码404,地址%@",webView.URL.absoluteString);
    }else {
        decisionHandler(WKNavigationResponsePolicyAllow);
        NSLog(@"成功码%ld,地址%@",statusCode,webView.URL.absoluteString);//允许加载
    }
    NSString *urlStr = webView.URL.absoluteString;
    NSLog(@"收到响应是否跳转:%@",urlStr);
  
}

//收到响应后是否执行动作
#pragma mark - WKWeb页面响应打电话
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSString *urlStr = webView.URL.absoluteString;
    decisionHandler(WKNavigationActionPolicyAllow);
    
}

#pragma mark - 允许弹出Alert(查看业主电话)
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{

}

- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{

}

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{

}

//--------------------------------------------------------------------------------------------------
#pragma mark - 超过60秒请求失败
- (void)delayMethod{
    [_webView stopLoading];
//    [self dismissLoading];
}


- (void)dealloc {
    [_webView removeObserver:self forKeyPath:@"estimatedProgress"];
    //清除缓存
    if ([[[UIDevice currentDevice] systemVersion]intValue ] > 8) {
        NSArray * types =@[WKWebsiteDataTypeMemoryCache,WKWebsiteDataTypeDiskCache]; // 9.0之后才有的
        NSSet *websiteDataTypes = [NSSet setWithArray:types];
        NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
        [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
        }];
    }else{
        NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask, YES) objectAtIndex:0];
        NSString *cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
        NSLog(@"%@", cookiesFolderPath);
        NSError *errors;
        [[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:&errors];
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 允许加载无证书验证的地址
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler {
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        if ([challenge previousFailureCount] == 0) {
            NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
            completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
        } else {
            completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
        }
    } else {
        completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
    }
}



@end
